<?php

namespace Biz\service\activity;

use Doraemon\service\position\UserProfileModule\PicNum;

/**
 * 获取活动数据 → 导入归档 → 删除原始数据 → 操作记录
* 归档数据重放 → 恢复活动数据 → 标记归档数据记录
* 后台读取(判断活动状态) → 首先读取归档数据 → 活动数据
 *
* 分段存储, 活动id + 类型 + 唯一标识
* 获取存储 活动id + 类型 + 唯一标识
*/
class ServeActivityArchive
{
    private int $maxDataLen = 65535;//65535 20
    private static $instance;
    const SPOTLIGHT_ACTIVITY_ID = \Biz\model\activity\ActivityAwardDelivery::ACTIVITY_SPOTLIGHT;

    public static function getInstance(): ServeActivityArchive
    {
        if (empty(self::$instance)) {
            self::$instance = new self;
        }
        return self::$instance;
    }

    public function hasArchive($activity_type): array
    {
        $list = \Biz\model\activity\ActivityArchive::select('*', ['activity_type' => $activity_type, 'status' => 0, 'GROUP' => 'activity_id']);
        $response = [];
        foreach ($list as $v) {
            $response[$v['activity_id']] = true;
        }
        return $response;
    }

    public function clearArchive($activity_type, $activity_id)
    {
        \Biz\model\activity\ActivityArchive::update(['status' => 9], ['activity_type' => $activity_type, 'activity_id' => $activity_id, 'status' => 0]);
    }

    public function saveArchive($activity_type, $activity_id, $uniq, $archive_data, $ext = '')
    {
        if (empty($archive_data)) return;
        $storeData = base64_encode(json_encode($archive_data, JSON_UNESCAPED_UNICODE));
        $len = ceil(strlen($storeData) / $this->maxDataLen);
        if ($len > 0) {
            foreach (range(1, $len) as $v) {
                $v -= 1;
                $tempData = substr($storeData, $v * $this->maxDataLen, $this->maxDataLen);
                $data = ['activity_type' => $activity_type, 'activity_id' => $activity_id, 'uniq' => $uniq, 'archive_data' => $tempData, 'ext' => $ext];
                \Biz\model\activity\ActivityArchive::addData($data);
            }
        }
    }

    public function getArchive($activity_type, $activity_id)
    {
        $list = \Biz\model\activity\ActivityArchive::select('*', ['activity_type' => $activity_type, 'activity_id' => $activity_id, 'status' => 0, 'ORDER' => 'id']);
        $data = [];
        foreach ($list as $v) {
            $data[$v['uniq']] .= $v['archive_data'];
        }

        $response = [];
        foreach ($data as $key => $v) {
            $response[$key] = $this->decrypt($v);
        }
        return $response;
    }

    private function decrypt($data)
    {
        return json_decode(base64_decode($data), true);
    }


}